package com.yoomiito.app.ui.gift;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.yoomiito.app.ImmersionBarFragment;
import com.yoomiito.app.MainActivity;
import com.yoomiito.app.R;
import com.yoomiito.app.base.App;
import com.yoomiito.app.base.BaseActivity;
import com.yoomiito.app.gift.GiftPresenter;
import com.yoomiito.app.gift.NewGiftAdapter;
import com.yoomiito.app.model.gift.GiftGoods;
import com.yoomiito.app.model.gift.GiftGoodsList;
import com.yoomiito.app.model.gift.GiftType;
import com.yoomiito.app.ui.goods.NewGoodsInfoActivity;
import com.yoomiito.app.utils.AllCode;
import com.yoomiito.app.utils.DensityUtil;
import com.yoomiito.app.utils.EventMessage;
import com.yoomiito.app.utils.Type;
import com.yoomiito.app.utils.UserInfoConfig;
import com.yoomiito.app.widget.ScrollLinearLayoutManager;
import com.yoomiito.app.widget.SpacingDecoration;
import com.yoomiito.app.widget.TabView;

import java.math.BigDecimal;
import java.util.List;

import butterknife.BindView;

/**
 * 399礼包
 */
public class GiftActivity extends BaseActivity<GiftPresenter> {
    public static final String GiftFragment = "gift_fragment";

    @BindView(R.id.act_gift_rcy)
    RecyclerView mRecyclerView;
    @BindView(R.id.title_bar)
    RelativeLayout titleBarParent;
    @BindView(R.id.iv_back_left)
    ImageView back;
    @BindView(R.id.tv_center)
    TextView titleTv;
    @BindView(R.id.fm_gift_1_titleBar)
    LinearLayout titlebarLl;
    @BindView(R.id.fm_gift_1_ll)
    LinearLayout mContainView;
    TabView mTabView;
    ImageView bgIv;
//    @BindView(R.id.bg_replace_view)
//    View mView;
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout mRefreshLayout;

    private NewGiftAdapter giftAdapter;
    private String sort = "";
    private int lastPage;
    private int currentPage = 1;
    private long type = 0;
    private List<GiftType> mGiftTypes;
    private int mGoodsType = 0;
    private LinearLayout ll;

    public static void start(Context context){
        Intent intent = new Intent(context,GiftActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.fm_gift_1;
    }

    @Override
    public GiftPresenter newP() {
        return new GiftPresenter(App.mAppConfig);
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        back.setOnClickListener(v -> finish());
//        initToolbar();
        initNotchScreen();
        initRcy();
        if (UserInfoConfig.getRoleId()>= Type.LevelType.VIP_7) {
            bgIv.setImageResource(R.drawable.gift_hy_bg_copy);
            titleTv.setText("品牌直供 品质严选");
        }else {
            bgIv.setImageResource(R.drawable.gift_hy_bg);
            titleTv.setText("品牌直供 品质严选");
        }
        initTabView();
        initRefreshLayout();
        getP().getVipGiftGoods(sort, currentPage, type, mGoodsType);
        getP().getGiftType(1);
    }

    private void initRefreshLayout() {
        mRefreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            getP().getVipGiftGoods(sort, currentPage, type, mGoodsType);
            getP().getGiftType(1);
        });
        mRefreshLayout.setOnLoadMoreListener(refreshLayout -> {
            currentPage++;
            getP().getVipGiftGoods(sort, currentPage, type, mGoodsType);
        });
    }

    int mBarHeight;
    private void initNotchScreen() {
//        if (ImmersionBar.hasNotchScreen(this)) {
            mBarHeight = ImmersionBar.getStatusBarHeight(this);
//            initBarHeight();
//        }else {
//            mView.setVisibility(View.GONE);
//        }
    }

    private void initBarHeight(){
//        LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) mView.getLayoutParams();
//        lp.height = mBarHeight;
//        mView.setLayoutParams(lp);
//        mView.setVisibility(View.VISIBLE);
    }

    private void initTabView() {
        mTabView.setDownName("_des")
                .setUpName("_asc")
                .setPriceFirstName("sale_price")
                .setSaleFirstName("volume")
                .showSort()
                .setDefault();
//        mTabView.setOnChangeListener((sort, hasCoupon) -> {
//            this.sort = sort;
//            currentPage = 1;
//            getP().getVipGiftGoods(sort, currentPage, type, mGoodsType);
//        });

        mTabView.setOnSortClickListener(giftType -> {
                    showLoading();
                    currentPage = 1;
                    type = giftType.getId();
                    getP().getVipGiftGoods(sort, currentPage, type, mGoodsType);
                }

        );
    }

    double scrollY = 0;
    private void initRcy() {
        ScrollLinearLayoutManager lm = new ScrollLinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
        mRecyclerView.setLayoutManager(lm);
        mRecyclerView.addItemDecoration(new SpacingDecoration(0,DensityUtil.dp2px(10),false));
        giftAdapter = new NewGiftAdapter(null, GiftFragment);
        View headerView = LayoutInflater.from(context).inflate(R.layout.item_gift_header, null);
        ll = headerView.findViewById(R.id.item_gift_header_ll);
        bgIv = headerView.findViewById(R.id.backdrop);
        mTabView  = (TabView) ll.getChildAt(0);
        mTabView.divVisible(false);
        giftAdapter.addHeaderView(headerView);
        mRecyclerView.setAdapter(giftAdapter);
        giftAdapter.setOnItemClickListener((adapter, view, position) ->
                        NewGoodsInfoActivity.Companion.toGoodsInfo(GiftActivity.this,String.valueOf(giftAdapter.getData().get(position).getId()),"2")
        );
//        giftAdapter.setOnLoadMoreListener(() -> {
//            currentPage++;
//            getP().getVipGiftGoods(sort, currentPage, type, mGoodsType);
//        }, mRecyclerView);

//        int mScrollY = DensityUtil.dp2px(140)-mBarHeight;
        int mScrollY = DensityUtil.dp2px(147);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {


            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                scrollY += dy;
                if (dy > 0) {//上滑
                    if (scrollY < mScrollY) {
//                        double p = scrollY / mScrollY;
//                        titlebarLl.setBackgroundColor(getColor("#E9D8C7", p));
                    }else {
                        if (mContainView.getChildCount()==0){
//                            titleBarParent.setVisibility(View.VISIBLE);
                            ll.removeAllViews();
                            mContainView.addView(mTabView);
                            mContainView.setBackgroundResource(R.color.color_white);
                        }
//                        titleBarParent.setBackgroundResource(R.color.color_gift_bg);
                    }
                }
                if (dy < 0) {//下滑
                    if (scrollY <= mScrollY) {
//                        double p = (scrollY) / mScrollY;
//                        titlebarLl.setBackgroundColor(getColor("#E9D8C7", p));
//                        titleBarParent.setBackgroundResource(R.color.color_tran);
                        if (ll.getChildCount()==0){
                            View view = mContainView.getChildAt(0);
                            mContainView.removeAllViews();
                            ll.addView(view);
                            mContainView.setBackgroundResource(R.color.color_tran);
//                            titleBarParent.setVisibility(View.INVISIBLE);
                        }
                        return;
                    }
                    if (scrollY >= mScrollY) {

                    }
                }

            }
        });
    }

    private int getColor(String color, double i) {
        if (i>1)i=1;
        BigDecimal bg = new BigDecimal(i);
        i = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        int alpha = (int) Math.round(i * 255);
        String hex = Integer.toHexString(alpha).toUpperCase();
        if (hex.length() == 1) hex = "0" + hex;
        StringBuilder sb = new StringBuilder(color);
        String newColor = sb.insert(1, hex).toString();
        return Color.parseColor(newColor);
    }

    public void showGift(GiftGoodsList goodsList) {
        List<GiftGoods> data = goodsList.getList().getData();
        if (giftAdapter==null){
            return;
        }
        if (currentPage == 1) {
            scrollY = 0;
            if (data==null||data.size()==0){//修复问题 当列表为空时 没有恢复原位 造成的显示异常问题
                mRecyclerView.scrollTo(0,0);
                titlebarLl.setBackgroundResource(R.color.color_tran);
                if (ll.getChildCount()==0){
                    View view = mContainView.getChildAt(0);
                    mContainView.removeAllViews();
                    ll.addView(view);
                    titleTv.setVisibility(View.INVISIBLE);
                }
            }
            giftAdapter.setNewData(data);
            mRefreshLayout.finishRefresh(true);
            mRefreshLayout.setNoMoreData(false);
        } else {
            mRefreshLayout.finishLoadMore(true);
            if (data == null || data.size() == 0) {
//                Toast.makeText(context, "没有更多了", Toast.LENGTH_SHORT).show();
                mRefreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                giftAdapter.addData(data);
            }
        }
    }

    public void setType(List<GiftType> types) {
        if (types != null) {
            mGiftTypes = types;
            mGiftTypes.add(0, new GiftType(0, "全部", true));
            mTabView.setGiftTypes(mGiftTypes);
        }
    }

    public void finishRefresh() {
        mRefreshLayout.finishLoadMore(true);
        mRefreshLayout.finishRefresh(true);
    }

    @Override
    public void eventMessage(EventMessage eventMessage) {
        super.eventMessage(eventMessage);
        if (AllCode.LoginOut.equals(eventMessage.getEventType())||
                AllCode.LoginSuccess.equals(eventMessage.getEventType())){
            currentPage = 1;
            getP().getVipGiftGoods(sort, currentPage, type, mGoodsType);
        }
    }

//    @Override
//    public void initImmersionBar() {
//        ImmersionBar.with(this).keyboardEnable(false).init();
//    }

}
